package com.snail.billing.page;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.android.util.ResUtil;
import com.snail.billing.Billing;
import com.snail.billing.DataCache;
import com.snail.billing.Resource;
import com.snail.billing.data.Account;
import com.snail.billing.data.AccountList;
import com.snail.billing.data.AccountManager;
import com.snail.billing.os.DialogPage;

public class LoginPage extends DialogPage implements View.OnClickListener, AdapterView.OnItemClickListener {

	private View buttonClose;

	private View layoutAccount;
	private TextView textAccount;
	private View buttonPopup;
	private View buttonLogin;
	private View buttonLoginOther;

	private PopupWindow popupWindow;
	private boolean isCreate;
	private int pwidth;
	private ListView listView;
	private SimpleAdapter adapter;
	private List<Map<String, String>> data;
	private AccountList accountList;
	private Account currentAccount;

	@Override
	public int createLayoutId() {
		return ResUtil.getLayoutId(Resource.layout.snailbilling_login_activity);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		buttonClose = findViewById(ResUtil.getViewId(Resource.id.snailbilling_title_button_close));
		buttonClose.setOnClickListener(this);
		//
		layoutAccount = findViewById(ResUtil.getViewId(Resource.id.snailbilling_login_layout_account));
		textAccount = (TextView) findViewById(ResUtil.getViewId(Resource.id.snailbilling_login_text_account));
		buttonPopup = findViewById(ResUtil.getViewId(Resource.id.snailbilling_login_button_popup));
		buttonLogin = findViewById(ResUtil.getViewId(Resource.id.snailbilling_login_button));
		buttonLoginOther = findViewById(ResUtil.getViewId(Resource.id.snailbilling_login_button_other));
		buttonPopup.setOnClickListener(this);
		buttonLogin.setOnClickListener(this);
		buttonLoginOther.setOnClickListener(this);
		//
		currentAccount = AccountManager.getCurrentAccount();
		if (currentAccount != null) {
			textAccount.setText(currentAccount.getAccount());
		}
		accountList = AccountManager.getAccountList();
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		dismissPopup();
		currentAccount = accountList.getAll().get(position);
		textAccount.setText(currentAccount.getAccount());
	}

	private void showPopup() {
		if (accountList.length() != 0) {
			popupWindow.showAsDropDown(layoutAccount);
		}
	}

	private void dismissPopup() {
		popupWindow.dismiss();
	}

	private void initDatas() {
		data = new ArrayList<Map<String, String>>();
		for (Account account : accountList.getAll()) {
			Map<String, String> map = new HashMap<String, String>();
			if (account.getType().equals(Account.TYPE_RANDOM) || account.getType().equals(Account.TYPE_RANDOM_OLD)) {
				map.put("account", ResUtil.getString(Resource.string.snailbilling_login_text_random) + account.getAccount());
			} else {
				map.put("account", account.getAccount());
			}
			data.add(map);
		}
	}

	private void initPopupWindow() {
		if (accountList.length() == 0) {
			return;
		}
		if (isCreate) {
			return;
		}
		isCreate = true;
		initDatas();
		LayoutInflater inflater = LayoutInflater.from(getContext());
		View view = inflater.inflate(ResUtil.getLayoutId(Resource.layout.snailbilling_login_popup_layout), null);
		listView = (ListView) view.findViewById(ResUtil.getViewId(Resource.id.snailbilling_login_popup_listview));
		listView.setOnItemClickListener(this);
		pwidth = layoutAccount.getWidth();
		popupWindow = new PopupWindow(view, pwidth, -2, true);
		popupWindow.setOutsideTouchable(true);
		popupWindow.setBackgroundDrawable(new ColorDrawable(0));
		int resource = ResUtil.getLayoutId(Resource.layout.snailbilling_login_popup_item);
		String[] from = { "account" };
		int[] to = { ResUtil.getViewId(Resource.id.snailbilling_login_popup_text) };
		adapter = new PopupAdapter(getContext(), data, resource, from, to);
		listView.setAdapter(adapter);
	}

	private class PopupAdapter extends SimpleAdapter {

		public PopupAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) {
			super(context, data, resource, from, to);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View view = super.getView(position, convertView, parent);
			View button = view.findViewById(ResUtil.getViewId(Resource.id.snailbilling_login_popup_button));
			final int index = position;
			button.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					dismissPopup();
					//
					final Dialog dialog = new Dialog(getContext());
					dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
					dialog.getWindow().setBackgroundDrawable(new ColorDrawable(0));
					dialog.setCancelable(true);
					dialog.setCanceledOnTouchOutside(false);
					//
					int orientation = getContext().getResources().getConfiguration().orientation;
					int screenWidth = getContext().getResources().getDisplayMetrics().widthPixels;
					int screenHeight = getContext().getResources().getDisplayMetrics().heightPixels;
					ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(screenWidth, screenHeight);
					if (orientation == Configuration.ORIENTATION_PORTRAIT) {
						int width = (int) (screenWidth * 0.9);
						int height = (int) (screenHeight * 0.6);
						params = new ViewGroup.LayoutParams(width, height);
					} else if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
						int width = (int) (screenWidth * 0.5);
						int height = (int) (screenWidth * 0.5 * 9 / 16);
						params = new ViewGroup.LayoutParams(width, height);
					}
					View view = LayoutInflater.from(getContext()).inflate(ResUtil.getLayoutId(Resource.layout.snailbilling_alert_dialog), null);
					dialog.setContentView(view, params);
					view.findViewById(ResUtil.getViewId(Resource.id.snailbilling_alert_dialog_cancel)).setOnClickListener(new View.OnClickListener() {

						@Override
						public void onClick(View v) {
							dialog.dismiss();
						}
					});
					view.findViewById(ResUtil.getViewId(Resource.id.snailbilling_alert_dialog_delete)).setOnClickListener(new View.OnClickListener() {

						@Override
						public void onClick(View v) {
							dialog.dismiss();
							if (index == 0) {
								AccountManager.clearCurrentAccount();
								currentAccount = null;
							}
							Account account = accountList.getAll().get(index);
							accountList.remove(account);
							AccountManager.removeAccount(account);
							textAccount.setText("");
							data.remove(index);
							adapter.notifyDataSetChanged();
						}
					});
					dialog.show();
				}
			});
			return view;
		}
	}

	@Override
	public void onClick(View v) {
		if (v.equals(buttonClose)) {
			getPageManager().finish();
		} else if (v.equals(buttonPopup)) {
			initPopupWindow();
			showPopup();
		} else if (v.equals(buttonLogin)) {
			if (currentAccount != null) {
				if (currentAccount.getType().equals(Account.TYPE_RANDOM) || currentAccount.getType().equals(Account.TYPE_RANDOM_OLD)) {
					AccountManager.setAccount(currentAccount);
					getPageManager().finish();
					DataCache.getInstance().importParams.pageClass = DialogUpdatePage.class;
					getContext().startActivity(new Intent(getContext(), Billing.class));
				} else {
					AccountManager.setAccount(currentAccount);
					getPageManager().finish();
					DataCache.getInstance().importParams.pageClass = DialogChangePage.class;
					Intent intent = new Intent(getContext(), Billing.class);
					intent.putExtra(DialogChangePage.ACCOUNT, currentAccount.getAccount());
					intent.putExtra(DialogChangePage.PWD, currentAccount.getPwd());
					intent.putExtra(DialogChangePage.TYPE, currentAccount.getType());
					getContext().startActivity(intent);
				}
			}
		} else if (v.equals(buttonLoginOther)) {
			getPageManager().forward(LaunchPage.class);
		}
	}

}
